from plugins.template import ParserTemplate
import re

def get_parsers():
	return {"Ershin" : Parser}

class Parser(ParserTemplate):
	"""
	Grammar:
	Page = "Page" Number ":" NL .
	Text = Translation NL.

	Remove {.*}, remove [ and ] (but keep things in between!)
	also remove japanese chars at start
	"""

	_PageRe = re.compile(r'''Page\ (\d+): 	# Page<blank><Number>:
	$ # end''', re.VERBOSE | re.IGNORECASE)
	
	def __init__(self, file):
		super().__init__(file)
	
	def _parse_next(self, last_token):
		try:
			page = self._parse_re(self._PageRe) or last_token.page
			panel = "?"
			line = self._cur_line
			text = self._parse_text()
			if not text:
				return self._parse_next(last_token)
			return [self.Token(page, panel, text, line)]
		except self.ParserEndError:
			return [None]

	def _parse_text(self):
		text = self._get_line()
		self._next_line()
		return self._remove_japanese_chars(re.sub(r"\[|]|{.*}|SFX|;", "", text)).strip()

#if __name__ == '__main__':
#	import doctest
#	doctest.testmod()

#from io import StringIO
#text = """
#Page 1:
#[The Secret Devil-chan]
#{*left side of page*} ["More! Secret Devil-chan" is currently being serialized in "Yaay! Mahalo"]
#{back to the right side} [Last time was terrible...]
#[In my eagerness to break my contract with Kogure, I ended up falling into a trap.  But soon the hunter became the hunted, and after things blew up a bit, we ended up right back where we started.]
#
#
#Page 2:
#The Secret Devil-chan
#Chapter 9: Devil-chan takes a make-up test
#{As spring arrives, things are going more and more smoothly!}
#{Emu}
#"""
#parser = Parser(StringIO(text))
#token = parser.next_token()
#while token:
#	print(token)
#	token = parser.next_token()
